<template>
    <div class="app-contain">
        <div style="border-bottom: 1px solid #e8e8e8;">
            <Toolbar style="border-bottom: 1px solid #ccc" :editor="editor1" :defaultConfig="toolbarConfig1" :mode="mode" />
            <Editor
                class="editor-container"
                id="editor1"
                v-loading="editorLoading1"
                v-model="html1"
                :defaultConfig="editorConfig1"
                :mode="mode"
                @onCreated="onCreated1"
                @onChange="onChange1"
                @customPaste="customPaste1"
            />
        </div>
        <div id="page1" style="display:none">
        </div>
    </div>
</template>

<script>
import {editDoc, saveEditDoc} from "@/api/compare/index"
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { Boot} from '@wangeditor/editor'
import { DomEditor } from '@wangeditor/editor'
import '@wangeditor/editor/dist/css/style.css'
import MySaveButtonMenu from './saveMenu.js'
//节点操作
import { SlateEditor, SlateElement, SlateNode } from '@wangeditor/editor'
// import axios from 'axios'
const saveConf = {
    key: 'saveVariable', // =====>要插入变量我是关键，记住我的名字
    factory () {
        return new MySaveButtonMenu()
    }
}
const module = {
    menus: [saveConf],
// 其他功能，下文讲解...
}
Boot.registerModule(module)

export default {
    components: {Editor, Toolbar},
    data() {
        return {
            editor1: null,
            imgSrc1: '',
            html1: '',
            editorLoading1: false,
            toolbarConfig1: {
                insertKeys: {
                    index: 0,
                    keys: ['saveVariable'] // ====>对应上文定义的key
                },
            },
            mode: 'default', // or 'simple'
            vHtml1: "",
            editorConfig1: {
                id: "editor1",
                placeholder: '',
                scroll: false, // 禁止编辑器滚动
                readOnly: false,
                MENU_CONF: {
                    uploadImage: {
                        fieldName: 'your-fileName',
                        base64LimitSize: 10 * 1024 * 1024 // 10M 以下插入 base64
                    },
                    fontSize: {
                        fontSizeList: ['5pt', '6pt', '7pt', '8pt', '9pt', '10pt', '10.5pt', '11pt', '12pt', '13pt', '14pt', '15pt', '16pt', '17pt', '18pt', '19pt', '20pt', '21pt', '22pt', '23pt', '24pt', '25pt', '26pt', '27pt', '28pt', '29pt', '30pt', '31pt', '32pt', '33pt', '34pt', '35pt', '36pt', '37pt', '38pt', '39pt', '40pt', '41pt', '42pt', '43pt', '44pt', '45pt', '46pt', '47pt', '48pt', '49pt']
                    },
                    fontFamily: {
                        fontFamilyList: ['宋体', '黑体', '楷体', 'Calibri', 'SimSun, STSon']
                    },
                }
            },
            isLeft: null,
            hasDoc: null,
            oldFileName: null,
            showDia: false,//标注弹窗
            remark: '',//备注
        }
    },
    mounted() {
        this.getHtmlFn();
    },
    watch:{
        $route:{
            handler(val){
                this.getHtmlFn();
            }
        }
    },
    beforeDestroy() {
        const editor1 = this.editor1;
        if (editor1) {
            editor1.destroy() // 组件销毁时，及时销毁编辑器
        }

    },
    methods: {
        getHtmlFn(){
            let editor = this.editor1;
            let opt = {
                id:this.$route.query.id
            }
            editDoc(opt).then(response => {
                console.log(response.data)
                this.editor1.dangerouslyInsertHtml(response.data);
            })
        },
        async fileChange(res) {
            console.log(res)
            // let page1 =  document.getElementById('page1').innerHTML;
            // // console.log(page1)
            // let page2 =  document.getElementById('page2').innerHTML;
            // console.log(page2)
            let editor1 = this.editor1;
            // this.editor1.focus()
            // this.html1 = page2;
            // // this.$nextTick(()=>{
            // this.editor1.focus()
            // this.editor1.dangerouslyInsertHtml(this.html1);
            // // })
            // console.log('file++++',res.srcElement.files)
            // // form-data 请求
            let formData = new FormData();
            let files = Array.from(res.srcElement.files); // files是类数组，需要先转为数组
            // alert(this.hasDoc==null)
            if (files.length == 1 && this.hasDoc == null) {
                this.oldFileName = files[0].name;  //暂存文件名称
                importFileName(files[0].name).then(res => {
                    console.log(res)
                    let html = res.origin;
                    let num1 = html.indexOf('<p');
                    let num2 = html.lastIndexOf('</p>') + 4;
                    var info = html.slice(num1, num2)
                    document.getElementById('page1').innerHTML = info;
                    let str = document.getElementById('page1').innerHTML;
                    if (this.isLeft == 1) {
                        // editor1.focus();
                        editor1.setHtml(str);
                    }
                    this.hasDoc = 1;
                })

            } else if (this.hasDoc) {
                importFile(this.oldFileName).then(res => {
                    console.log("res.compare=====", res.compare)
                    let html1 = res.compare;
                    let html2 = res.origin;   //yuanshi
                    let num11 = html1.indexOf('<p');
                    let num21 = html2.indexOf('<p');
                    // console.log(num1)
                    let num12 = html1.lastIndexOf('</p>') + 4;
                    let num22 = html2.lastIndexOf('</p>') + 4;
                    // console.log(num2)
                    var aa = html1.slice(num11, num12)
                    var bb = html2.slice(num21, num22)
                    // console.log(aa)
                    document.getElementById('page1').innerHTML = aa;
                    document.getElementById('page3').innerHTML = bb;
                    let str = document.getElementById('page1').innerHTML;  //new
                    let str2 = document.getElementById('page3').innerHTML;  //old
                    var regExp = new RegExp('\n', 'g');
                    var newStr = str.replace(regExp, '')
                    console.log(str)
                    if (this.isLeft == 1) {  //说明最新上传的是点的左边，原始文件展示应在右边
                        // editor1.focus();
                        editor1.setHtml(newStr);
                        // editor2.focus();
                        editor2.setHtml(str2);
                    } else {
                        // editor1.focus();
                        editor1.setHtml(str2);
                        // editor2.focus();
                        editor2.setHtml(newStr);
                    }


                    // var obj = document.getElementById('changeFile') ;
                    // obj.outerHTML=obj.outerHTML;

                }).catch(ero => {
                    console.log(ero)
                })
            }


            // console.log(formData)
            // axios.post('upload', formData,{'Content-Type': 'multipart/form-data'}) // 设置请求头，确保服务器正确解析 FormData})
            // .then((res) => {
            //     console.log('数据：', res);
            // })


            // if (res.srcElement.files && res.srcElement.files.length > 0) {//如果有要上传的文件
            //     const file = res.srcElement.files[0]//因为是单选，所以只需要取第一个
            //     const word = ['docx']//word文件的格式
            //     const nameArr = file.name.split('.')//取文件名的后缀
            //     let status = false
            //     status = word.some((element) => {//如果文件名的后缀在word文件格式内，则进行解析word
            //         return element === nameArr[nameArr.length - 1]//文件名的后缀
            //     })
            //     if (status) {
            //         const value = await this.analysisWord(res.srcElement.files[0])//解析word
            //         const editor = this.editor
            //         console.log(value)
            //         editor.dangerouslyInsertHtml(value)//粘贴html格式的内容
            //     } else {
            //         this.$message.warning('暂仅支持.docx文件格式')
            //     }
            //     res.target.value = ''
            // }
        },
        analysisWord(file) {
            console.log(file)
        },
        onCreated1(editor) {
            this.editor1 = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
            // this.editor1.on('showVariable', this.showVariable)//监听上传功能
            this.editor1.on('saveEditor', this.saveEditor)//监听保存功能
            // this.editor1.on('editEditor', this.editEditor)//监听修改功能
            // this.editor1.on('markEditor', this.markEditor)//监听修改功能

            // 查看工具栏的默认配置
            this.$nextTick(() => {
                const toolbar = DomEditor.getToolbar(this.editor1)
                console.log(toolbar)
                const curToolbarConfig = toolbar.getConfig()
                console.log("curToolbarConfig.toolbarKeys===", curToolbarConfig.toolbarKeys) // 当前菜单排序和分组


            })
        },
        onChange1(editor) {
            console.log("editor", editor)
            // console.log("top!!!!!!===",document.getElementById('1').getBoundingClientRect().top)
            var scrollTop = window.pageYOffset || document.documentElement.scrollTop
            //获取选中的节点
            const nodeEntries = SlateEditor.nodes(this.editor1, {
                match: (node) => {
                    console.log("node----------", node)
                    console.log("selection", this.editor1.selection)
                    //判断一个节点是否是 elem
                    if (SlateElement.isElement(node)) {
                        // 获取一个节点对应的 DOM 节点
                        console.log("this.editor1.toDOMNode(node)===", this.editor1.toDOMNode(node))
                        console.log("node.id========", this.editor1.toDOMNode(node).id)
                        if (node.type === 'paragraph') {
                            return true // 匹配 paragraph
                        }
                    }
                    return false
                },
                universal: true,
            })
            if (nodeEntries == null) {
                console.log('当前未选中的 paragraph')
            } else {
                console.log("当前选中的")
                for (let nodeEntry of nodeEntries) {
                    const [node, path] = nodeEntry
                    console.log('选中了 paragraph 节点', node)
                    // console.log('节点 path 是', path)
                }
            }
        },

        onCreated2(editor) {
            this.editor2 = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
            this.editor2.on('showVariable', this.showVariable2)//监听上传功能
            this.editor2.on('saveEditor', this.saveEditor2)//监听保存功能
            this.editor2.on('editEditor', this.editEditor2)//监听修改功能
        },
        onChange2(editor) {
            console.log(editor)
            console.log(document.getElementById('1'))
            //获取选中的节点
            const nodeEntries = SlateEditor.nodes(this.editor2, {
                match: (node) => {
                    console.log("node----------", node)
                    //判断一个节点是否是 elem
                    if (SlateElement.isElement(node)) {
                        // 获取一个节点对应的 DOM 节点
                        //const elem = editor.toDOMNode(node) // 返回 HTMLElement
                        console.log("this.editor2.toDOMNode(node)===", this.editor2.toDOMNode(node))
                        console.log("parentNode = ", this.editor2.getParentNode(node))

                        // this.idddd = this.editor1.toDOMNode(node).id
                        console.log("node.id========", this.editor2.toDOMNode(node).id)
                        if (node.type === 'paragraph') {
                            return true // 匹配 paragraph
                        }
                    }
                    return false
                },
                universal: true,
            })
            if (nodeEntries == null) {
                console.log('当前未选中的 paragraph')
            } else {
                console.log("当前选中的")
                for (let nodeEntry of nodeEntries) {
                    const [node, path] = nodeEntry
                    console.log('选中了 paragraph 节点', node)
                    // console.log('节点 path 是', path)
                }
            }
        },
        //自定义粘贴。可阻止编辑器的默认粘贴，实现自己的粘贴逻辑。
        async customPaste1(editor, event) {
            this.editorLoading1 = true;
            // event 是 ClipboardEvent 类型，可以拿到粘贴的数据
            // 可参考 https://developer.mozilla.org/zh-CN/docs/Web/API/ClipboardEvent
            let html = event.clipboardData.getData('text/html') // 获取粘贴的 html
            const rtf = event.clipboardData.getData('text/rtf') // 获取 rtf 数据（如从 word wsp 复制粘贴）
            if (html && rtf) {
                // 列表缩进会超出边框，直接过滤掉
                // html = html.replace(/text\-indent:\-(.*?)pt/gi, '')
                // 从html内容中查找粘贴内容中是否有图片元素，并返回img标签的属性src值的集合
                const imgSrcs = this.findAllImgSrcsFromHtml(html);
                // 如果有
                if (imgSrcs && Array.isArray(imgSrcs) && imgSrcs.length) {
                    // 从rtf内容中查找图片数据
                    const rtfImageData = this.extractImageDataFromRtf(rtf);
                    // 如果找到
                    if (rtfImageData.length) {
                        // TODO：此处可以将图片上传到自己的服务器上
                        // 执行替换：将html内容中的img标签的src替换成ref中的图片数据，如果上面上传了则为图片路径
                        html = await this.replaceImagesFileSourceWithInlineRepresentation(html, imgSrcs, rtfImageData)
                        // console.log(html)
                        editor.dangerouslyInsertHtml(html);
                        // 阻止默认的粘贴行为
                        this.editorLoading1 = false;
                        event.preventDefault()
                        return false
                    }
                }
            }
            this.editorLoading1 = false;
            return true;
        },
        //自定义粘贴。可阻止编辑器的默认粘贴，实现自己的粘贴逻辑。
        async customPaste2(editor, event) {
            this.editorLoading2 = true;
            // event 是 ClipboardEvent 类型，可以拿到粘贴的数据
            // 可参考 https://developer.mozilla.org/zh-CN/docs/Web/API/ClipboardEvent
            let html = event.clipboardData.getData('text/html') // 获取粘贴的 html
            const rtf = event.clipboardData.getData('text/rtf') // 获取 rtf 数据（如从 word wsp 复制粘贴）
            if (html && rtf) {
                // 列表缩进会超出边框，直接过滤掉
                // html = html.replace(/text\-indent:\-(.*?)pt/gi, '')
                // 从html内容中查找粘贴内容中是否有图片元素，并返回img标签的属性src值的集合
                const imgSrcs = this.findAllImgSrcsFromHtml(html);
                // 如果有
                if (imgSrcs && Array.isArray(imgSrcs) && imgSrcs.length) {
                    // 从rtf内容中查找图片数据
                    const rtfImageData = this.extractImageDataFromRtf(rtf);
                    // 如果找到
                    if (rtfImageData.length) {

                        // TODO：此处可以将图片上传到自己的服务器上

                        // 执行替换：将html内容中的img标签的src替换成ref中的图片数据，如果上面上传了则为图片路径
                        html = await this.replaceImagesFileSourceWithInlineRepresentation(html, imgSrcs, rtfImageData)
                        // console.log(html)
                        editor.dangerouslyInsertHtml(html);
                        // 阻止默认的粘贴行为
                        this.editorLoading2 = false;

                        event.preventDefault()
                        return false

                    }
                }

            }
            this.editorLoading2 = false;
            return true;
        },
        //上传文件
        showVariable() {
            this.isLeft = 1;
            const changeFile = document.getElementById("changeFile")
            changeFile.click();
        },
        // 编辑
        editEditor() {
            this.editor1.enable();
        },
        // 保存
        saveEditor() {
            let opt={
                fileId:this.$route.query.fileId,
                whichFlag:this.$route.query.whichFlag,
                htmlString:this.editor1.getHtml()
            }
            saveEditDoc(opt).then(() => {
                this.$modal.msgSuccess("保存成功");
                // this.$router.go(-1);
            });
            // this.editor1.disable();
        },
        markEditor() {
            //this.editor1()
            this.showDia = true;
        },
        confrimMark() {
            this.showDia = false;
            console.log("操作标记mark标签")
            console.log(this.editor1.isFocused())
            this.editor1.focus()
            this.editor1.dangerouslyInsertHtml(`<span style="color:red;font-weight:700;">批注</span>`)
            //此处缺少跟后端交互的接口
            /*
                思路：新添加一个标注的icon,跟后端交互将标注保存到后台
                怎么展示？
                    选中标注的符号，前端根据选中的node的id进行判断
                    例如id: mark-2222
                    前端判断如果id中包含'mark' 则调用后端接口并显示弹窗展示标注
                    否则不展示
                是否删除？
                    如果删除，需要在弹窗中增加一个删除按钮 调用后端删除接口操作
            */

        },


        //上传文件
        showVariable2() {
            this.isLeft = 2;
            const changeFile = document.getElementById("changeFile")
            changeFile.click();
        },
        // 编辑
        editEditor2() {
            this.editor2.enable();
        },
        // 保存
        saveEditor2() {
            this.editor2.disable();
        }
    }
}
</script>
<style src="@wangeditor/editor/dist/css/style.css" important></style>
<style>
html,
body {
    background-color: #fff;
    height: 100%;
    overflow: hidden;
    color: #333;
}

.app-contain {
    background-color: rgb(245, 245, 245);
}

.editor-container {
    height: 78vh;
    overflow-y: auto;
    position: relative;
    background-color: #fff;
}

/* .editor-container {
  width: 100%;
  min-height: 900px;
  margin: 30px auto 150px auto;
  background-color: #fff;
  padding: 20px 50px 50px 50px;
  border: 1px solid #e8e8e8;
  box-shadow: 0 2px 10px rgba(0,0,0,12%);
} */
::v-deep strong {
    font-weight: bold !important;
}

::v-deep .italic {
    font-style: italic !important;
}

::v-deep ol {
    list-style: decimal
}

/* 问题：H1-H5样式不生效
  修改思路：重置样式
  相关文件：Editor.vue
*/
::v-deep h1 {
    font-size: 2em;
    font-weight: bold;
}

::v-deep h2 {
    font-size: 1.5em;
    font-weight: bold;
}

::v-deep h3 {
    font-size: 1.17em;
    font-weight: bold;
}

::v-deep h4 {
    font-weight: bold;
}

::v-deep h5 {
    font-size: 0.83em;
    font-weight: bold;
}

.w-e-full-screen-container {
    z-index: 999;
}
</style>
